
<template>
  <view class="notification-container">
    <!-- 顶部导航 -->
    <view class="nav-header">
      <view class="nav-back" @tap="goBack">
        <text class="back-icon">〈</text>
      </view>
      <text class="nav-title">消息通知</text>
      <view class="nav-right" @tap="clearAllRead">
        <text v-if="hasUnread">全部已读</text>
      </view>
    </view>
    
    <!-- 分类选项卡 -->
    <view class="tab-container">
      <view 
        class="tab-item" 
        :class="{'tab-active': activeTab === 'all'}" 
        @tap="switchTab('all')">
        <text>全部</text>
      </view>
      <view 
        class="tab-item" 
        :class="{'tab-active': activeTab === 'system'}" 
        @tap="switchTab('system')">
        <text>系统通知</text>
      </view>
      <view 
        class="tab-item" 
        :class="{'tab-active': activeTab === 'activity'}" 
        @tap="switchTab('activity')">
        <text>活动消息</text>
      </view>
      <view 
        class="tab-item" 
        :class="{'tab-active': activeTab === 'order'}" 
        @tap="switchTab('order')">
        <text>订单消息</text>
      </view>
    </view>
    
    <!-- 消息列表 -->
    <scroll-view class="notification-list" scroll-y @scrolltolower="loadMore">
      <!-- 日期分组 -->
      <block v-for="(group, date) in groupedNotifications" :key="date">
        <view class="date-divider">
          <view class="date-line"></view>
          <text class="date-text">{{formatDate(date)}}</text>
          <view class="date-line"></view>
        </view>
        
        <!-- 消息项 -->
        <view 
          class="notification-item" 
          :class="{'unread': !item.isRead}" 
          v-for="(item, index) in group" 
          :key="index"
          @tap="readNotification(item)">
          <view class="notification-icon-container">
            <view 
              class="notification-icon" 
              :class="{
                'system-icon': item.type === 'system',
                'activity-icon': item.type === 'activity',
                'order-icon': item.type === 'order'
              }">
              <image :src="getIconByType(item.type)" class="icon-image"></image>
            </view>
            <view class="unread-dot" v-if="!item.isRead"></view>
          </view>
          
          <view class="notification-content">
            <view class="notification-header">
              <text class="notification-title">{{item.title}}</text>
              <text class="notification-time">{{formatTime(item.time)}}</text>
            </view>
            <text class="notification-desc">{{item.content}}</text>
            
            <!-- 可点击操作区域 -->
            <view class="notification-actions" v-if="item.actionType">
              <view 
                class="action-btn" 
                v-if="item.actionType === 'order'"
                @tap.stop="viewOrder(item.actionParams)">
                <text>查看订单</text>
              </view>
              <view 
                class="action-btn" 
                v-if="item.actionType === 'activity'"
                @tap.stop="viewActivity(item.actionParams)">
                <text>参与活动</text>
              </view>
              <view 
                class="action-btn" 
                v-if="item.actionType === 'coupon'"
                @tap.stop="viewCoupon(item.actionParams)">
                <text>领取优惠</text>
              </view>
            </view>
          </view>
        </view>
      </block>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="isLoading">
        <view class="loading-icon"></view>
        <text class="loading-text">加载中...</text>
      </view>
      
      <!-- 无更多数据 -->
      <view class="end-line" v-if="noMoreData && notifications.length > 0">
        <text>- 禅意茶语，静待花开 -</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="notifications.length === 0 && !isLoading">
        <image class="empty-icon" src="/static/icons/empty-notification.png"></image>
        <text class="empty-text">暂无消息通知</text>
        <text class="empty-desc">来一杯清茶，静候好消息</text>
      </view>
    </scroll-view>
    
    <!-- 删除确认弹窗 -->
    <view class="confirm-modal" v-if="showDeleteModal">
      <view class="modal-mask" @tap="closeDeleteModal"></view>
      <view class="confirm-content">
        <text class="confirm-title">清空消息</text>
        <text class="confirm-text">确定要清空所有消息吗？</text>
        <view class="confirm-btns">
          <view class="confirm-btn cancel-btn" @tap="closeDeleteModal">取消</view>
          <view class="confirm-btn delete-btn" @tap="confirmClearAll">清空</view>
        </view>
      </view>
    </view>
    
    <!-- 消息详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="modal-mask" @tap="closeDetailModal"></view>
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{currentDetail.title}}</text>
          <text class="close-btn" @tap="closeDetailModal">×</text>
        </view>
        <view class="detail-time">{{formatFullTime(currentDetail.time)}}</view>
        <rich-text class="detail-body" :nodes="currentDetail.fullContent || currentDetail.content"></rich-text>
        
        <view class="detail-actions" v-if="currentDetail.actionType">
          <view 
            class="detail-action-btn" 
            v-if="currentDetail.actionType === 'order'"
            @tap="viewOrder(currentDetail.actionParams)">
            <text>查看订单</text>
          </view>
          <view 
            class="detail-action-btn" 
            v-if="currentDetail.actionType === 'activity'"
            @tap="viewActivity(currentDetail.actionParams)">
            <text>参与活动</text>
          </view>
          <view 
            class="detail-action-btn" 
            v-if="currentDetail.actionType === 'coupon'"
            @tap="viewCoupon(currentDetail.actionParams)">
            <text>领取优惠</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'all',
      notifications: [],
      isLoading: false,
      noMoreData: false,
      page: 1,
      pageSize: 10,
      showDeleteModal: false,
      showDetailModal: false,
      currentDetail: {},
      
      // 示例数据
      mockNotifications: [
        {
          id: 1,
          type: 'system',
          title: '系统升级通知',
          content: '尊敬的用户，我们将于2023年5月20日凌晨2点-4点进行系统升级维护，期间可能影响部分功能使用。',
          fullContent: '<div style="line-height: 1.6;">尊敬的用户：<br><br>为提升您的使用体验，我们将于2023年5月20日凌晨2:00-4:00进行系统升级维护。<br><br>在此期间，您可能无法正常使用购物、支付等功能，请您提前做好安排。<br><br>感谢您的理解与支持！<br><br>禅境团队</div>',
          time: new Date('2023-05-18 10:00:00'),
          isRead: true,
          actionType: null,
          actionParams: null
        },
        {
          id: 2,
          type: 'activity',
          title: '禅意插花课程开启',
          content: '一花一世界，邀您参加本周六下午2点的禅意插花课程，静心体验花艺之美。',
          fullContent: '<div style="line-height: 1.6;">禅心雅意，花开见性<br><br>禅境特邀日本池坊流派花道大师亲临指导，为您带来一场心灵与美学的盛宴。<br><br>【课程信息】<br>时间：2023年5月27日（周六）14:00-16:00<br>地点：禅境茶舍西湖店<br>费用：会员299元/人（含所有花材和茶点）<br><br>名额有限，报名从速！</div>',
          time: new Date('2023-05-25 15:30:00'),
          isRead: false,
          actionType: 'activity',
          actionParams: { activityId: 'a001' }
        },
        {
          id: 3,
          type: 'order',
          title: '订单发货通知',
          content: '您购买的【禅意茶具套装】已发货，物流单号：SF1234567890，预计3-5天送达。',
          time: new Date('2023-05-26 09:15:00'),
          isRead: false,
          actionType: 'order',
          actionParams: { orderId: 'o12345' }
        },
        {
          id: 4,
          type: 'system',
          title: '会员升级通知',
          content: '恭喜您成功升级为禅境银禅会员，可享受9折购物优惠及专属活动邀请。',
          time: new Date('2023-05-26 16:45:00'),
          isRead: false,
          actionType: null,
          actionParams: null
        },
        {
          id: 5,
          type: 'activity',
          title: '限时优惠券',
          content: '感恩回馈，我们为您准备了一张满300减50的优惠券，有效期7天，请及时使用。',
          time: new Date('2023-05-27 11:20:00'),
          isRead: false,
          actionType: 'coupon',
          actionParams: { couponId: 'c789' }
        },
        {
          id: 6,
          type: 'order',
          title: '订单已签收',
          content: '您购买的【禅韵香道套装】已签收，感谢您的购买，希望您对此次购物体验满意。',
          time: new Date('2023-05-27 14:30:00'),
          isRead: true,
          actionType: 'order',
          actionParams: { orderId: 'o12346' }
        },
        {
          id: 7,
          type: 'system',
          title: '账户安全提醒',
          content: '您的账户于今日10:30在新设备登录，如非本人操作，请及时修改密码。',
          time: new Date('2023-05-28 10:35:00'),
          isRead: true,
          actionType: null,
          actionParams: null
        }
      ]
    }
  },
  computed: {
    // 分组后的消息列表（按日期）
    groupedNotifications() {
      const grouped = {};
      const filteredNotifications = this.getFilteredNotifications();
      
      filteredNotifications.forEach(item => {
        const dateStr = this.getDateStr(item.time);
        if (!grouped[dateStr]) {
          grouped[dateStr] = [];
        }
        grouped[dateStr].push(item);
      });
      
      // 对日期键进行排序（降序）
      return Object.keys(grouped)
        .sort((a, b) => new Date(b) - new Date(a))
        .reduce((obj, key) => {
          obj[key] = grouped[key];
          return obj;
        }, {});
    },
    
    // 是否有未读消息
    hasUnread() {
      return this.notifications.some(item => !item.isRead);
    }
  },
  mounted() {
    this.loadNotifications();
  },
  methods: {
    // 导航方法
    goBack() {
      uni.navigateBack();
    },
    
    // 加载消息数据
    loadNotifications() {
      this.isLoading = true;
      
      // 模拟API请求延迟
      setTimeout(() => {
        // 实际项目中应该调用API获取数据
        // 这里使用模拟数据
        this.notifications = [...this.mockNotifications];
        this.isLoading = false;
        this.noMoreData = true;  // 示例数据已全部加载
      }, 500);
    },
    
    // 根据当前选中的标签筛选消息
    getFilteredNotifications() {
      if (this.activeTab === 'all') {
        return this.notifications;
      } else {
        return this.notifications.filter(item => item.type === this.activeTab);
      }
    },
    
    // 切换标签
    switchTab(tab) {
      this.activeTab = tab;
    },
    
    // 加载更多消息
    loadMore() {
      if (this.isLoading || this.noMoreData) return;
      
      this.isLoading = true;
      this.page += 1;
      
      // 模拟API请求
      setTimeout(() => {
        // 实际项目中应该调用API加载更多数据
        // 这里假设没有更多数据了
        this.isLoading = false;
        this.noMoreData = true;
      }, 500);
    },
    
    // 阅读消息
    readNotification(item) {
      // 标记为已读
      const index = this.notifications.findIndex(n => n.id === item.id);
      if (index !== -1) {
        this.notifications[index].isRead = true;
      }
      
      // 打开详情模态框
      this.currentDetail = item;
      this.showDetailModal = true;
      
      // 实际项目中应该调用API更新已读状态
    },
    
    // 清空消息（全部标记为已读）
    clearAllRead() {
      if (!this.hasUnread) return;
      this.showDeleteModal = true;
    },
    
    closeDeleteModal() {
      this.showDeleteModal = false;
    },
    
    confirmClearAll() {
      // 将所有消息标记为已读
      this.notifications.forEach(item => {
        item.isRead = true;
      });
      
      this.closeDeleteModal();
      
      uni.showToast({
        title: '已全部标记为已读',
        icon: 'success'
      });
      
      // 实际项目中应该调用API更新已读状态
    },
    
    // 关闭详情模态框
    closeDetailModal() {
      this.showDetailModal = false;
    },
    
    // 日期格式化方法
    getDateStr(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    
    formatDate(dateStr) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      
      const yesterday = new Date(today);
      yesterday.setDate(yesterday.getDate() - 1);
      
      const date = new Date(dateStr);
      date.setHours(0, 0, 0, 0);
      
      if (date.getTime() === today.getTime()) {
        return '今天';
      } else if (date.getTime() === yesterday.getTime()) {
        return '昨天';
      } else {
        return dateStr.replace(/-/g, '.');
      }
    },
    
    formatTime(date) {
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    
    formatFullTime(date) {
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${this.formatTime(date)}`;
    },
    
    // 根据消息类型获取图标
    getIconByType(type) {
      const iconMap = {
        'system': '/static/icons/notification-system.png',
        'activity': '/static/icons/notification-activity.png',
        'order': '/static/icons/notification-order.png'
      };
      
      return iconMap[type] || iconMap.system;
    },
    
    // 操作按钮方法
    viewOrder(params) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${params.orderId}`
      });
      this.closeDetailModal();
    },
    
    viewActivity(params) {
      uni.navigateTo({
        url: `/pages/activity/detail?id=${params.activityId}`
      });
      this.closeDetailModal();
    },
    
    viewCoupon(params) {
      uni.navigateTo({
        url: `/pages/coupon/detail?id=${params.couponId}`
      });
      this.closeDetailModal();
    }
  }
}
</script>

<style>
.notification-container {
  background-color: #F8F5F0; /* 米白色背景 */
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航 */
.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 88rpx;
  background-color: #F8F5F0;
  border-bottom: 1px solid #EEEAE3;
  padding: 0 30rpx;
  position: sticky;
  top: 0;
  z-index: 10;
}

.nav-back {
  width: 50rpx;
  height: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #5C4B3A;
}

.nav-title {
  font-size: 32rpx;
  color: #5C4B3A;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
  font-weight: bold;
}

.nav-right {
  font-size: 26rpx;
  color: #5C8D69; /* 青瓷绿 */
  font-family: "思源宋体", sans-serif;
}

/* 分类选项卡 */
.tab-container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: #FFFFFF;
  padding: 20rpx 0;
  border-bottom: 1px solid #EEEAE3;
}

.tab-item {
  position: relative;
  padding: 10rpx 0;
}

.tab-item text {
  font-size: 28rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

.tab-active text {
  color: #5C4B3A;
  font-weight: bold;
}

.tab-active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 4rpx;
  background-color: #5C8D69; /* 青瓷绿 */
  border-radius: 2rpx;
}

/* 消息列表 */
.notification-list {
  flex: 1;
  padding: 4rpx;
}

/* 日期分隔线 */
.date-divider {
  display: flex;
  align-items: center;
  margin: 30rpx 0;
}

.date-line {
  flex: 1;
  height: 1px;
  background-color: #EEEAE3;
}

.date-text {
  padding: 0 20rpx;
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

/* 消息项 */
.notification-item {
  display: flex;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.unread {
  background-color: rgba(232, 200, 114, 0.1); /* 佛经黄的淡化背景 */
}

.notification-icon-container {
  position: relative;
  margin-right: 20rpx;
}

.notification-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.system-icon {
  background-color: rgba(92, 141, 105, 0.1); /* 淡青瓷绿 */
}

.activity-icon {
  background-color: rgba(232, 200, 114, 0.1); /* 淡佛经黄 */
}

.order-icon {
  background-color: rgba(123, 127, 201, 0.1); /* 淡紫色 */
}

.icon-image {
  width: 40rpx;
  height: 40rpx;
}

.unread-dot {
  position: absolute;
  top: 0;
  right: 0;
  width: 16rpx;
  height: 16rpx;
  background-color: #E76F51; /* 暖红色 */
  border-radius: 8rpx;
}

.notification-content {
  flex: 1;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10rpx;
}

.notification-title {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  font-weight: bold;
}

.notification-time {
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

.notification-desc {
  font-size: 26rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  line-height: 1.5;
  margin-bottom: 16rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.notification-actions {
  display: flex;
  justify-content: flex-end;
}

.action-btn {
  background-color: rgba(92, 141, 105, 0.1); /* 淡青瓷绿 */
  padding: 6rpx 20rpx;
  border-radius: 20rpx;
}

.action-btn text {
  font-size: 24rpx;
  color: #5C8D69; /* 青瓷绿 */
  font-family: "思源宋体", sans-serif;
}

/* 加载状态 */
.loading-state {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
}

.loading-icon {
  width: 30rpx;
  height: 30rpx;
  border: 2px solid #EEEAE3;
  border-top: 2px solid #5C8D69;
  border-radius: 50%;
  margin-right: 10rpx;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

/* 列表底部 */
.end-line {
  text-align: center;
  padding: 30rpx 0;
}

.end-line text {
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
}

/* 确认弹窗 */
.confirm-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.confirm-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 560rpx;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
}

.confirm-title {
  font-size: 32rpx;
  color: #5C4B3A;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30rpx;
}

.confirm-text {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  text-align: center;
  margin-bottom: 40rpx;
}

.confirm-btns {
  display: flex;
}

.confirm-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-family: "思源宋体", sans-serif;
}

.cancel-btn {
  background-color: #EEEAE3;
  color: #8C7B68;
  margin-right: 20rpx;
}

.delete-btn {
  background-color: #5C8D69; /* 青瓷绿 */
  color: #FFFFFF;
}

/* 详情弹窗 */
.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
}

.detail-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 680rpx;
  max-height: 80vh;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  padding: 40rpx 30rpx;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.detail-title {
  font-size: 32rpx;
  color: #5C4B3A;
  font-family: "汉仪尚巍手书", "思源宋体", sans-serif;
  font-weight: bold;
}

.close-btn {
  font-size: 40rpx;
  color: #8C7B68;
  padding: 10rpx;
}

.detail-time {
  font-size: 24rpx;
  color: #8C7B68;
  font-family: "思源宋体", sans-serif;
  margin-bottom: 20rpx;
  border-bottom: 1px solid #EEEAE3;
  padding-bottom: 20rpx;
}

.detail-body {
  font-size: 28rpx;
  color: #5C4B3A;
  font-family: "思源宋体", sans-serif;
  line-height: 1.6;
  margin-bottom: 30rpx;
}

.detail-actions {
  display: flex;
  justify-content: center;
  margin-top: 40rpx;
}

.detail-action-btn {
  background-color: #5C8D69; /* 青瓷绿 */
  color: #FFFFFF;
  padding: 16rpx 60rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-family: "思源宋体", sans-serif;
  box-shadow: 0 2rpx 10rpx rgba(92, 141, 105, 0.3);
}
</style>